<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试 WebSocket</title>
</head>
<body>

    <form onsubmit="return false">
        <textarea name="message" style="height:300px;width:300px"></textarea>
        <input type="button" value="发送消息" onclick="send(this.form.message.value)"/>
        <textarea id="responseText" style="width: 300px;height:300px"></textarea>
        <input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''">
    </form>

    <script>
        const supportWebsocket = isWebsocket();// 检测当前浏览器是否支持 websocket
        let socket;

        if(supportWebsocket){
            let resEl = document.getElementById('responseText');
            console.log('获取到的 textarea:');
            console.log(resEl);
            socket = new WebSocket("ws://localhost:7000/hello");
            socket.onmessage = function(event){
                resEl.value = resEl.value + '\n' + event.data;
            }

            socket.onopen = function(event){
                console.log('连接到 websocket 服务端了')
                resEl.value = '连接开启了...';
            }

            socket.onclose = function(event){
                resEl.value = resEl.value + '\n' + '连接关闭了...';
            }
        }else{
            alert('当前浏览器不支持 websocket!');
        }


        function send(msg){
            if(!socket){
                alert('websocket还没有创建好！');
                return;
            }

            if(socket.readyState !== WebSocket.OPEN) {
                alert('websocket连接还没有开启！');
                return;
            }
            socket.send(msg);
        }

        function isWebsocket() {
            if (!!window.WebSocket && window.WebSocket.prototype.send) return true;
            else return false;
        }
    </script>

</body>
</html>